# app/core/user_database.py
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from contextlib import asynccontextmanager
from app.core.config import settings
import logging

logger = logging.getLogger(__name__)

# 创建异步用户数据库引擎
user_engine = create_async_engine(
    settings.DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://") if "postgresql" in settings.DATABASE_URL else settings.DATABASE_URL,
    pool_size=100,
    max_overflow=50,
    pool_timeout=30,
    pool_recycle=300,
    pool_pre_ping=True
)

# 创建异步用户会话工厂
UserSessionLocal = sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=user_engine,
    class_=AsyncSession
)

@asynccontextmanager
async def get_user_db_context():
    """异步用户数据库上下文管理器"""
    async with UserSessionLocal() as db:
        try:
            yield db
        finally:
            await db.close()

# 用于FastAPI依赖注入
async def get_user_db():
    async with get_user_db_context() as db:
        yield db